//
//  SingleSingleST_PeculiarityDetialSupplementView.swift
//  btvideo
//
//  Created by mac on 2020/2/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import HandyJSON
import SwiftyUserDefaults




/**只有基础控件
 */
class ST_SinglePeculiarityDetialBaseSupplementView: UICollectionReusableView {
    

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = Color.white
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(77)
        }
        
        
        self.addSubview(right_image_view)
        right_image_view.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel)
            make.left.equalTo(titleLabel.snp.right).offset(5)
        }
        
        self.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.width.height.equalTo(50)
        }
        
        
        self.addSubview(user_name_label)
        user_name_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(avatar_image_view.snp.bottom).offset(10)
        }
        
        self.addSubview(pecSubLabel)
        pecSubLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview().offset(-12)
            make.top.equalTo(user_name_label.snp.bottom).offset(5)
        }
        
        
        self.avatar_image_view.isUserInteractionEnabled = true
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(lookHandle))
        
        self.avatar_image_view.addGestureRecognizer(tap)
        
    }
    
    @objc fileprivate func lookHandle(){
        
        guard let accid = dataModel?.information?.accid else { return  }
        
        if accid == Defaults[.currentUserID]{
            return
        }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.clipsToBounds = true
        control.cornerRadius = 25
        return control
    }()
    
    
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hex: 0x333333)
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 28, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var user_name_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    /**特质描述*/
    fileprivate lazy var pecSubLabel:UITextField = {
        let control = UITextField.init()
        control.text = ""
        control.textAlignment = .center
        let attrString = NSMutableAttributedString(string: "添加你的特质描述")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.attributedPlaceholder = attrString
        control.textColor = Color.init(hexString: "#61666F")
        control.tintColor = Color.init(hexString: "#61666F")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.isUserInteractionEnabled = false
        control.delegate = self
        return control
    }()
    
//    fileprivate lazy var pecSubLabel:UILabel = {
//        let control = UILabel.init()
//        control.text = ""
//        control.textColor = Color.init(hexString: "#61666F")
//        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
//        return control
//    }()
    
    fileprivate lazy var right_image_view:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("个人中心_icon_向后一页")
        control.isHidden = true
        return control
    }()
    
    //    MARK: - Bind Model
    var dataModel:SinglePrcDetialModel?{
        didSet{
            
            guard let userinfo = dataModel?.information,let peculiarity = dataModel?.feature_detail else { return }
            
            titleLabel.text = peculiarity.name
            
            avatar_image_view.pin_setImage(from: userinfo.avatar.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            user_name_label.text = userinfo.nickname
            
            pecSubLabel.text = peculiarity.remark
            
            right_image_view.isHidden = userinfo.accid != Defaults[.currentUserID]
            
//            别人 不展示
            if userinfo.accid != Defaults[.currentUserID] {
                if peculiarity.remark.isEmpty{
                    pecSubLabel.isHidden = true
                }
            }
        }
    }
}

extension ST_SinglePeculiarityDetialBaseSupplementView:UITextFieldDelegate{
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        print("编辑 完成 textField:",textField.text ?? "")
        
        guard let str = textField.text,str.isEmpty == false,let peculiarity = dataModel?.feature_detail else { return }
        
        let param = ["feature_id":peculiarity.id,"remark":str] as [String : Any]
        
        JVrequest(PH.modifyRemarkApi, parameters: param, success: { (json) in
            
            NotificationCenter.default.post(name: Notification.Name.my_pairs_user_info_updated, object: nil)
            
        }) { (code, err) in
            ToastHud(text: err, view: self.parentViewController?.view)
        }
        
    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard var animal = textField.text else{
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: string)
         
            return animal.count <= 24
            
        }else{
            return true
        }
        
        
    }
}



//MARK: - 带 查看和 喜欢 按钮

class SingleOtherPeculiaritySupplementView: ST_SinglePeculiarityDetialBaseSupplementView {
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(love_btn)
        
        self.addSubview(look_btn)
        
        love_btn.snp.makeConstraints { (make) in
            make.top.equalTo(pecSubLabel.snp.bottom).offset(20-5)
            make.width.equalTo(80)
            make.height.equalTo(35)
            make.left.equalTo(self.snp.centerX).offset(10)
        }
        
        look_btn.snp.makeConstraints { (make) in
            make.height.top.width.equalTo(love_btn)
            make.right.equalTo(self.snp.centerX).offset(-10)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 35/2.0
        control.setTitleForAllStates("喜欢")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var look_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#F2F4F7")
        control.cornerRadius = 35/2.0
        control.setTitleForAllStates("查看")
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(lookHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
}


extension SingleOtherPeculiaritySupplementView{
    
    @objc fileprivate func love_handle(){
        
        guard let info = dataModel?.information,let peculiarity = dataModel?.feature_detail else { return  }
           
        let user = ST_MatchUserInfo.init(accid: info.accid, avatar: info.avatar, nickname: info.nickname)
     
        
        self.parentViewController?.likeBehavior(info: user, isLike: true, loveSquare: false, loveWay: ST_LoveWay.peculiarity, peculiarity: peculiarity.id.string, responseClosure: { (success) in
            
            
            ToastHud(text: "喜欢成功", view: self.parentViewController?.view)
        })
        
    }
    
    
    
}

//MARK: - 带 编辑按钮

class SingleEditPeculiaritySupplementView: ST_SinglePeculiarityDetialBaseSupplementView {
    
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(add_btn)
        
        add_btn.snp.makeConstraints { (make) in
            make.top.equalTo(pecSubLabel.snp.bottom).offset(20-5)
            make.width.equalTo(80)
            make.height.equalTo(35)
            make.centerX.equalToSuperview()
        }
        
        self.addSubview(sign_image_view)
        sign_image_view.snp.makeConstraints { (make) in
            make.centerY.equalTo(pecSubLabel).offset(-4)
            make.centerX.equalToSuperview().offset(73-12)
        }
        
        self.addSubview(animate_image_view)
        animate_image_view.snp.makeConstraints { (make) in
            make.centerY.equalTo(sign_image_view)
            make.left.equalTo(sign_image_view.snp.right)
        }
        
        self.pecSubLabel.isUserInteractionEnabled = true
        
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_child_handle))
        self.right_image_view.isUserInteractionEnabled = true
        self.right_image_view.addGestureRecognizer(tap)
        
        let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(push_child_handle))
        self.titleLabel.isUserInteractionEnabled = true
        self.titleLabel.addGestureRecognizer(tap1)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var dataModel: SinglePrcDetialModel?{
        didSet{

            if let str = dataModel?.feature_detail?.remark,!str.isEmpty{

               let offSet = str.width(withConstrainedHeight: 100, font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular))

                sign_image_view.snp.updateConstraints { (make) in
                    make.centerX.equalToSuperview().offset(offSet/2.0+5+10-12)
                }
                
                
                self.animate_image_view.isHidden = true
                self.animate_image_view.layer.removeAllAnimations()
            }else{
                
                self.animate_image_view.isHidden = false
                self.bounce_animation()
            }
            
            sign_image_view.isHidden = false
        }
    }
    
    
    fileprivate lazy var add_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 35/2.0
        control.setTitleForAllStates("添加")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(add_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var sign_image_view:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.set_back_image_for_all_states(ST_ImageUtils.imageName("首页_icon_编辑描述")!)
        control.isHidden = true
        control.addTarget(self, action: #selector(start_edit_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        if newSuperview == nil{
            self.animate_image_view.layer.removeAllAnimations()
        }
        
    }
    
    fileprivate lazy var animate_image_view:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.isUserInteractionEnabled = false
        control.set_back_image_for_all_states(ST_ImageUtils.imageName("add_pec_animate_icon")!)
        control.isHidden = true
        return control
    }()
    
    
    fileprivate func bounce_animation(){
           
        
        UIView.animate(withDuration: 0.75, animations: {
            
            self.animate_image_view.transform = CGAffineTransform.init(translationX: 0, y: 4)
            
        }) { (f) in
            
            
            UIView.animate(withDuration: 0.55, animations: {
                
                self.animate_image_view.transform = CGAffineTransform.identity
                
            }) { (f) in
                
//                main_thread_execute(afterDelay: 0.5) {
                    self.bounce_animation()
//                }
            }
            
        }
        
    }
    
    @objc fileprivate func start_edit_handle(){
        self.pecSubLabel.becomeFirstResponder()
    }
    
    @objc fileprivate func push_child_handle(){
        
        guard let peculiarity = dataModel?.feature_detail else{
            return
        }
        
        let peculiarity_id = peculiarity.id
        
        var sameGender = false
//        同性
        if peculiarity.type == ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex?.rawValue{
            sameGender = true
        }
        
        
        push_peculiarity(id: peculiarity_id, onlyDisplayPerson: sameGender, isToday: false, navigationController: self.parentViewController?.navigationController)
    }
    
    @objc fileprivate func add_handle(){
        
        guard let peculiarity_id = dataModel?.feature_detail?.id else{
            return
        }
         
        self.parentViewController?.show_indeterminate_h_u_d()
        
        let param = ["feature_id":peculiarity_id]
                
        JVrequest(PH.fetchCurrPeculiarityNodesApi,parameters:param, success: { (json) in
            
            print("发布详情调接口:",json)
            
            let data = json["data"]
            
            let dataStr = data["node_list"].rawString() ?? ""
            
            if let willPushNode = [ST_PeculiarityModel].deserialize(from: dataStr)?.first as? ST_PeculiarityModel{
                
                willPushPeculiarity = willPushNode
                
                if let remark = self.dataModel?.feature_detail?.remark{
                    willPushPeculiarity?.remark = remark
                }
                
                push_peculiarity(navigationController: self.parentViewController?.navigationController, operationController: ST_PushPeculiaritySelectMediaController())
                
            }
            
            self.parentViewController?.hidden_indeterminate_h_u_d()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.parentViewController?.view)
        }
    }
    
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        sign_image_view.isHidden = true
        
    }
    
}



struct SinglePrcDetialModel:HandyJSON {
    
    var feature_detail:ST_PeculiarityModel?
    var information:ST_BTUserinfo?
    var total = 0
}
